package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    private final CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //最终返回的数据列表
        List<CourseCategoryTreeDto> courseCategoryList=new ArrayList<>();

        //拿出所有的数据
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
                                                                                //排除父节点
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos.stream().filter(item ->! id.equals(item.getId()))
                                                                            //当key重复时，以新的为主
                .collect(Collectors.toMap(key-> key.getId(), value -> value, (key1, key2) -> key2));


        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //判断是否为二级节点，是的话直接向返回表里添加
            if (item.getParentid().equals(id)){
                courseCategoryList.add(item);
            }

            //根据其父节点,将其父节点内容获取出来
            CourseCategoryTreeDto courseCategoryTreeDto = map.get(item.getParentid());

            //集合里的数据不能为空
            if (courseCategoryTreeDto!=null){
                //如果子节点为null的话就创建一个空的数组去替换---这样就可以存放子节点数据了
                if (courseCategoryTreeDto.getChildrenTreeNodes()==null){
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //添加子节点
                courseCategoryTreeDto.getChildrenTreeNodes().add(item);
            }
        });

        return courseCategoryList;




    }
}
